import React from 'react';
import { Carousel, Image, message, Card, Comment, List, Input, Avatar, Select, Space, Tag, Divider, Button } from 'antd';
import { Url } from '../url';
import axios from 'axios';

import { BankOutlined, FireOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { AskService } from '../ask/ask-mangement';

const { Meta } = Card;

const { Option } = Select;


const { Search } = Input;

const contentStyle = {
    height: '50vh',
    width: "100vw",
    color: '#fff',
    textAlign: 'center',
    background: '#364d79'
};
export class Home extends React.Component {
    state = {
        askList: [],
        selectedCategoryList: [],
        initSelectList: [],
        minBudget: undefined,
        maxBudget: undefined,
        searchValue: "",
        advanceSearch: "none"
    }

    componentDidMount = () => {
        this.getAskList();
    }

    getAskList = () => {
        axios.get(Url.askAll).then(
            (response) => {
                this.setState({
                    askList: [...response.data],
                    selectedCategoryList: [...new Set(response.data.map(ask => ask.category))],
                    initSelectList: [...new Set(response.data.map(ask => ask.category))]
                });
            })
            .catch((error) => {
                message.error("Network Error");
            });
    }

    formatDollar = (dollar) => {
        const dollarArray = String(dollar).split(".");
        const dollarInteger = dollarArray[0];
        let dollarDecimal = dollarArray[1];
        if (dollarDecimal == undefined) {
            dollarDecimal = "00"
        }
        return <span><span style={{ fontSize: "11px" }}>{"$ "}</span><span>{dollarInteger + "."}</span><span style={{ fontSize: "12px" }}>{dollarDecimal}</span></span>;
    }

    handleCategoryChange = (selectedCategoryList) => {
        this.setState({
            selectedCategoryList: [...selectedCategoryList]
        })
        console.log(selectedCategoryList)

    }

    onMinBudgetChange = (event) => {
        this.setState({
            "minBudget": event.target.value
        });
    }

    onMaxBudgetChange = (event) => {

        this.setState({
            "maxBudget": event.target.value
        });
    }

    onSearch = (value) => {
        this.setState({
            searchValue: value.target.value
        });
    }

    showAdvaneSearch = () => {
        if (this.state.advanceSearch === "none") {
            this.setState({
                advanceSearch: "show"
            });
        } else {
            this.setState({
                advanceSearch: "none"
            });
        }
    }

    render = () => {

        const coverList = this.state.askList.filter(each => each.state !== "cancel")
        .sort((a, b) => a.publishTime - b.publishTime).map(each => `${Url.viewImage + each.cover}`).slice(0, 4);

        const coverImages = coverList.map(each => {
            return (
                <div>
                    <div style={{
                        position: "absolute",
                        height: '50vh',
                        width: "100vw",
                        color: '#fff',
                        textAlign: 'center',
                        zIndex: 10000
                    }}>
                        <Image
                            height={"100%"}
                            src={each}
                        />
                    </div>
                    <div style={{
                        height: '50vh',
                        width: "100vw",
                        color: '#fff',
                        textAlign: 'center',
                        backgroundImage: `url('${each}')`,
                        backgroundColor: "#364d79",
                        filter: `blur(15px)`
                    }}>
                    </div>
                </div >
            )
        });

        const activeList = this.state.askList.map(each => {
            if (each.winBid) {
                return {
                    "type": "win",
                    "name": each.winBid.user.name,
                    "detail": `Congratulate ${each.winBid.user.name} won the project ${each.name}.`,
                    "activeTime": each.winBid.winTime
                }
            } else {
                return {
                    "type": "publish",
                    "name": each.company,
                    "detail": `${each.company} has published a new project ${each.name}.`,
                    "activeTime": each.publishTime
                }
            }
        }).sort((a, b) => {
            return b.activeTime - a.activeTime;
        });

        const gridStyle = {
            width: '33%',
            textAlign: 'center',
        };


        const categoryOptions = [...new Set(this.state.askList.map(ask => ask.category))].map(each => {
            return <Option key={each}>{each}</Option>
        });

        const getStateTag = (ask) => {
            const state = AskService.getAskState(ask);
            if (state === "ready") {
                return <Tag color="purple" icon={<FireOutlined />}>Ready</Tag>
            } else if (state === "start") {
                return <Tag color="green" icon={<FireOutlined />}>In progress</Tag>
            } else if (state === "cancel") {
                return <Tag icon={<MinusCircleOutlined />} color="default">Canceled</Tag>
            } else if (state === "finish") {
                return <Tag icon={<MinusCircleOutlined />} color="default">Finished</Tag>
            } else {
                return <Tag icon={<MinusCircleOutlined />} color="default">Stopped</Tag>
            }
        }

        const askList = this.state.askList.filter(each => {
            const minBudget = this.state.minBudget ? Number(this.state.minBudget) : -1;
            const maxBudget = this.state.maxBudget ? Number(this.state.maxBudget) : Number.MAX_VALUE;

            return each.state !== "cancel" && this.state.selectedCategoryList.includes(each.category) && each.cost >= minBudget && each.cost <= maxBudget
                && (each.name.toLowerCase().includes(this.state.searchValue.toLowerCase()) || each.company.toLowerCase().includes(this.state.searchValue.toLowerCase()))
        }).sort((a, b) => a.publishTime - b.publishTime).map(each => {
            return <Card.Grid style={gridStyle}>
                <Card
                    hoverable={false}
                    bordered={false}
                    cover={<img src={Url.viewImage + each.cover} />}
                    bodyStyle={{ textAlign: 'left' }}
                >
                    <Meta title={<div style={{ marginTop: "10px", textAlign: "left", fontSize: "13px" }}>
                        <a href={"/#/ask/" + each.askId} style={{ color: "black" }}> {each.name} </a>
                        {getStateTag(each)}
                    </div>}
                        description={<div>
                            <span style={{ color: "darkred", textAlign: "left", fontWeight: "bold" }}>{this.formatDollar(each.cost)}</span>
                            <span style={{ float: "right", fontWeight: "bold" }}>{each.bidList ? each.bidList.length : 0} bids</span>
                        </div>}
                    />
                    <div style={{ marginTop: "16px" }}><BankOutlined /> <span style={{ marginLeft: "4px" }}>{each.company}</span></div>
                </Card>
            </Card.Grid>
        })

        const colorList = ['#f56a00', '#7265e6', '#ffbf00', '#00a2ae'];

        const advanceSearchStyle = { marginBottom: "16px", display: this.state.advanceSearch }

        let advanceSearchBody = <div></div>
        if (this.state.advanceSearch === "show") {
            advanceSearchBody = <div style={advanceSearchStyle}>
                <span style={{ marginRight: "8px", fontWeight: "bold" }}>Category:</span>
                <Select mode="tags" style={{ width: '30%' }} placeholder="Catagory" onChange={this.handleCategoryChange} value={this.state.selectedCategoryList}>
                    {categoryOptions}
                </Select>
                <Space>
                    <span style={{ marginRight: "8px", fontWeight: "bold", marginLeft: "16px" }}>Budget Range:</span>
                    <Input.Group compact style={{ display: "inline-block" }}>
                        <Input style={{ width: 100, textAlign: 'center' }} placeholder="Minimum"
                            onChange={this.onMinBudgetChange} />
                        <Input
                            style={{
                                width: 30,
                                borderLeft: 0,
                                borderRight: 0,
                                pointerEvents: 'none',
                                backgroundColor: "#fff"
                            }}
                            placeholder="~"
                            disabled
                        />
                        <Input
                            style={{
                                width: 100,
                                textAlign: 'center',
                                borderLeftWidth: 0
                            }}
                            placeholder="Maximum"
                            onChange={this.onMaxBudgetChange}
                        />
                    </Input.Group>
                </Space>

            </div>
        }

        return (
            <div style={{ overflowX: "hidden", backgroundColor: "#f0f0f0" }}>
                <Carousel autoplay>
                    {coverImages}
                </Carousel>

                <div style={{ display: 'flex', justifyContent: "center", width: "100vw", }}>
                    <div style={{ width: "70%", backgroundColor: "white", paddingLeft: "32px", paddingRight: "32px" }}>
                        <Divider orientation="left"><div style={{ fontSize: "22px" }}>Search</div></Divider>
                        <Search placeholder="Project name/ Company" onChange={this.onSearch} style={{ marginBottom: "16px" }} />
                        <Button type="link" size="small" onClick={this.showAdvaneSearch}>Advance</Button>
                        {advanceSearchBody}
                        <Divider orientation="left"><div style={{ fontSize: "22px" }}>Projects</div></Divider>
                        <Card bordered={false}>
                            {askList}
                        </Card>

                        <Divider orientation="left"><div style={{ fontSize: "22px" }}>Activities</div></Divider>
                        <Card bordered={true} style={{ width: "100%" }}>
                            <List
                                itemLayout="horizontal"
                                dataSource={activeList}
                                renderItem={item => (
                                    <li>
                                        <Comment
                                            avatar={
                                                <Avatar style={{ backgroundColor: colorList[Math.floor(Math.random() * 4)], verticalAlign: 'middle' }}>
                                                    {item.name?item.name.slice(0, 1).toUpperCase():""}
                                                </Avatar>
                                            }
                                            content={item.detail}
                                            datetime={new Date(item.activeTime).toLocaleDateString() + " " + (new Date(item.activeTime)).toLocaleTimeString()}
                                        />
                                    </li>
                                )}
                            />
                        </Card>
                    </div>
                </div>
            </div >
        )
    }
}